from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.authentication import TokenAuthentication
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.utils import timezone
from .models import Community, Owner, Maintenance, Announcement, SystemSetting
from .serializers import (
    CommunitySerializer, OwnerSerializer, MaintenanceSerializer,
    AnnouncementSerializer, SystemSettingSerializer, UserSerializer, LoginSerializer
)

# 小区管理视图集
class CommunityViewSet(viewsets.ModelViewSet):
    queryset = Community.objects.all()
    serializer_class = CommunitySerializer
    permission_classes = [AllowAny]  # 开发环境允许未认证访问
    
    def finalize_response(self, request, response, *args, **kwargs):
        # 禁用缓存
        response['Cache-Control'] = 'no-cache, no-store, must-revalidate'
        response['Pragma'] = 'no-cache'
        response['Expires'] = '0'
        return super().finalize_response(request, response, *args, **kwargs)
    
    # 自定义的统计接口
    @action(detail=False, methods=['get'])
    def statistics(self, request):
        total = self.queryset.count()
        return Response({
            'total_communities': total
        })

# 业主管理视图集
class OwnerViewSet(viewsets.ModelViewSet):
    queryset = Owner.objects.all()
    serializer_class = OwnerSerializer
    permission_classes = [AllowAny]  # 允许未认证访问，便于前端测试
    
    def finalize_response(self, request, response, *args, **kwargs):
        # 禁用缓存
        response['Cache-Control'] = 'no-cache, no-store, must-revalidate'
        response['Pragma'] = 'no-cache'
        response['Expires'] = '0'
        return super().finalize_response(request, response, *args, **kwargs)
    
    def get_queryset(self):
        # 支持按小区筛选
        queryset = super().get_queryset()
        community_id = self.request.query_params.get('community_id')
        if community_id:
            queryset = queryset.filter(community_id=community_id)
        return queryset
    
    # 激活/禁用业主
    @action(detail=True, methods=['post'])
    def toggle_status(self, request, pk=None):
        owner = self.get_object()
        owner.is_active = not owner.is_active
        owner.save()
        return Response({
            'id': owner.id,
            'is_active': owner.is_active
        })

# 报修管理视图集
class MaintenanceViewSet(viewsets.ModelViewSet):
    queryset = Maintenance.objects.all()
    serializer_class = MaintenanceSerializer
    permission_classes = [IsAuthenticated]
    
    def get_queryset(self):
        # 支持按状态、业主、类型筛选
        queryset = super().get_queryset()
        status = self.request.query_params.get('status')
        owner_id = self.request.query_params.get('owner_id')
        type = self.request.query_params.get('type')
        
        if status:
            queryset = queryset.filter(status=status)
        if owner_id:
            queryset = queryset.filter(owner_id=owner_id)
        if type:
            queryset = queryset.filter(type=type)
            
        return queryset
    
    # 更新报修状态
    @action(detail=True, methods=['post'])
    def update_status(self, request, pk=None):
        maintenance = self.get_object()
        new_status = request.data.get('status')
        
        if new_status not in dict(Maintenance.STATUS_CHOICES):
            return Response({'error': '无效的状态值'}, status=status.HTTP_400_BAD_REQUEST)
        
        maintenance.status = new_status
        
        if new_status == 'processing' and maintenance.status != 'processing':
            maintenance.processing_time = timezone.now()
            maintenance.handler = request.user
        elif new_status == 'completed' and maintenance.status != 'completed':
            maintenance.completion_time = timezone.now()
        
        maintenance.save()
        return Response(self.get_serializer(maintenance).data)
    
    # 统计报修数据
    @action(detail=False, methods=['get'])
    def statistics(self, request):
        total = self.queryset.count()
        pending = self.queryset.filter(status='pending').count()
        processing = self.queryset.filter(status='processing').count()
        completed = self.queryset.filter(status='completed').count()
        rejected = self.queryset.filter(status='rejected').count()
        
        return Response({
            'total': total,
            'pending': pending,
            'processing': processing,
            'completed': completed,
            'rejected': rejected
        })

# 公告管理视图集
class AnnouncementViewSet(viewsets.ModelViewSet):
    queryset = Announcement.objects.all()
    serializer_class = AnnouncementSerializer
    permission_classes = [AllowAny]  # 开发环境允许未认证访问
    
    def perform_create(self, serializer):
        # 自动设置发布人，如果用户已登录则使用当前用户，否则使用系统默认用户
        from django.contrib.auth.models import User
        try:
            if self.request.user.is_authenticated and hasattr(self.request.user, 'pk'):
                publisher = self.request.user
            else:
                # 创建系统用户作为默认发布者
                # 确保设置密码，因为Django要求用户有密码
                publisher, created = User.objects.get_or_create(
                    username='system',
                    defaults={
                        'email': 'system@example.com', 
                        'is_staff': True,
                        'is_active': True,
                        'password': '!systempassword123'  # 实际项目中应该使用更安全的密码设置方式
                    }
                )
                # 如果用户是新创建的，设置密码哈希
                if created:
                    publisher.set_password('systempassword123')
                    publisher.save()
            # 明确设置发布者
            serializer.save(publisher=publisher)
        except Exception as e:
            # 记录详细错误信息
            print(f"创建公告时设置发布者错误: {type(e).__name__}: {e}")
            # 再次尝试，不设置发布者（如果模型允许）
            try:
                serializer.save()
            except Exception as inner_e:
                print(f"保存公告失败: {type(inner_e).__name__}: {inner_e}")
                raise
    
    def get_queryset(self):
        # 支持按类型筛选
        queryset = super().get_queryset()
        type = self.request.query_params.get('type')
        if type:
            queryset = queryset.filter(type=type)
        return queryset
    
    # 查看公告详情并增加浏览次数
    @action(detail=True, methods=['get'])
    def detail(self, request, pk=None):
        announcement = self.get_object()
        announcement.views_count += 1
        announcement.save()
        return Response(self.get_serializer(announcement).data)
    
    # 置顶/取消置顶
    @action(detail=True, methods=['post'])
    def toggle_sticky(self, request, pk=None):
        announcement = self.get_object()
        announcement.is_sticky = not announcement.is_sticky
        announcement.save()
        return Response({
            'id': announcement.id,
            'is_sticky': announcement.is_sticky
        })

# 系统设置视图集（单例模式）
class SystemSettingViewSet(viewsets.ModelViewSet):
    queryset = SystemSetting.objects.all()
    serializer_class = SystemSettingSerializer
    permission_classes = [IsAuthenticated]
    
    def get_object(self):
        # 确保只有一个系统设置实例
        obj, created = SystemSetting.objects.get_or_create(pk=1)
        return obj
    
    def perform_update(self, serializer):
        # 自动设置更新人和更新时间
        serializer.save(updated_by=self.request.user, updated_at=timezone.now())

# 认证相关视图
class AuthViewSet(viewsets.ViewSet):
    permission_classes = [AllowAny]
    
    # 登录接口
    @action(detail=False, methods=['post'])
    def login(self, request):
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid():
            username = serializer.validated_data['username']
            password = serializer.validated_data['password']
            
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                return Response({
                    'user': UserSerializer(user).data,
                    'message': '登录成功'
                })
            else:
                return Response({
                    'error': '用户名或密码错误'
                }, status=status.HTTP_401_UNAUTHORIZED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    # 登出接口
    @action(detail=False, methods=['post'], permission_classes=[IsAuthenticated])
    def logout(self, request):
        logout(request)
        return Response({'message': '登出成功'})
    
    # 获取当前用户信息
    @action(detail=False, methods=['get'], permission_classes=[IsAuthenticated])
    def profile(self, request):
        user = request.user
        return Response(UserSerializer(user).data)
